package com.example.utils;

import com.example.observer.Observer;

import java.rmi.NotBoundException;
import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;

public class ObserverHelper {
    
    private String host;
    private int port;

    public static final int DEFAULT_PORT = 20086;
    public static final String DEFAULT_HOST = "localhost";

    public ObserverHelper(String host, int port) {
        this.host = host;
        this.port = port;
    }
    
    public ObserverHelper() {
        this(DEFAULT_HOST, DEFAULT_PORT);
    }

    /**
     * 使用本地服务器
     * 
     * @param port 对应的端口
     */
    public ObserverHelper(int port) {
        this(DEFAULT_HOST, port);
    }

    /**
     * 根据注册时候的名字 获取对应的 observer
     * 
     * @param name
     * @return 名字对应的observer
     * @throws RemoteException
     * @throws NotBoundException
     */
    public Observer getRegisteredObserver(String name) throws RemoteException, NotBoundException {

        Registry registry = LocateRegistry.getRegistry(host, port);
        return (Observer) registry.lookup(name);
    }

    /**
     * 注册对象
     * 
     * @param name observer的名字，当获取这个observer的时候，需要这个name获取
     * @param observer
     * @throws RemoteException
     */
    public void registerObserver(String name, Observer observer) throws RemoteException {
        // 修复使用远程的observer时候出现主机错误的问题
        System.setProperty("java.rmi.server.hostname",host);

        // anonymous port // 如果继承了UnicastRemoteObject对象的话，这条语句就不是必须的了。
        Observer stub = (Observer) UnicastRemoteObject.exportObject(observer, 0);

        // 绑定服务名字和服务对象
        Registry registry = LocateRegistry.createRegistry(port);
        registry.rebind(name, stub);
    }
}
